<template>
  <div>
    <el-form ref="form" :model="form_" :label-width="labelWidth" :disabled="disabled">
      <el-form-item inline :prop="item.prop" :required="item.required ? item.required :false" :rules="rules(item)"
                    :label="item.label+'：'" :key="index" v-for="(item,index) in formConfig_.list">
        <component
          clearable
          :limit="limit(item)"
          :disabled="item.disabled"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :maxlength="item.maxlength"
          style="width: 100%"
          :min="0"
          :type="item.componentType"
          :is="item.component"
          :placeholder="(item.component === 'el-input' || item.component === 'el-input-number'?'请输入':'请选择')+item.label"
          v-model="form_[item.prop]">
          <template v-if="item.component === 'el-select'">
            <el-option
              v-for="(e,idx) in  item.options"
              :key="idx"
              :label="item.optionsKeys ? e[item.optionsKeys.label] : e.label"
              :value="item.optionsKeys ? e[item.optionsKeys.value] : e.value">
            </el-option>
          </template>
        </component>
      </el-form-item>
      <span v-if="formConfig_.desc" style="color: #C0C4CC">{{ formConfig_.desc }}</span>
    </el-form>
    <div class="flex-row-center-col-center p-5" v-if="showButon">
      <el-button v-if="showCancel" @click="$emit('cancel')">取消</el-button>
      <el-button v-if="showConfirm" type="primary" @click="confirm">保存</el-button>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import atools from "./index";

export default {
  nmae: 'aForm',
  components: {},
  props: {
    formConfig: {
      type: Object,
      default: () => {
      }
    },
    form: {
      type: Object,
      default: () => {
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    status: {
      type: String,
      default: ''
    },
    showButon: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    limit() {
      return function (e) {
        return e?.props?.limit ?? 1
      }
    },
    labelWidth() {
      return this.formConfig_?.props?.labelWidth ?? '120px'
    },
    rules() {
      return function (e) {
        const rules = e?.rules
        if (rules) {
          if (typeof rules === 'string') {
            if (rules === 'number') {
              let numbers = [
                {type: 'number', message: e.label + '必须为数字值'}
              ]
              if (e.required) {
                numbers = [...numbers, {required: true, message: e.label + '不能为空'},]
              }
              return numbers
            }
            if (rules === 'idCard') {
              return [{
                validator: atools.ckeckIdCard,
                trigger: ['blur', 'change'],
                label: e.label,
                required: e.required
              }]
            }
            if (rules === 'postCard') {
              return [{
                validator: atools.checkPostCard,
                trigger: ['blur', 'change'],
                label: e.label,
                required: e.required
              }]
            }
            if (rules === 'rePassword') {
              return [{
                validator: atools.checkPassword,
                trigger: ['blur', 'change'],
                label: e.label,
                required: e.required
              }]
            }

            if (rules === 'password') {
              return [{
                validator: atools.checkPassword,
                trigger: ['blur', 'change'],
                label: e.label,
                required: e.required
              }]
            }
            if (rules === 'phone') {
              return [{validator: atools.checkPhone, trigger: ['blur', 'change'], label: e.label, required: e.required}]
            }
            if (rules === 'email') {
              return [{validator: atools.checkEmail, trigger: ['blur', 'change'], label: e.label, required: e.required}]
            }
          }
          if (Array.isArray(e)) {
            return e
          }
          if (typeof e === 'function') {
            return [{validator: e, trigger: 'blur', label: e.label, required: e.required}]
          }
        } else {
          return [{
            required: e.required,
            message: (e.component === 'el-input' || e.component === 'el-input-number' ? '请输入' : '请选择') + e.label,
            trigger: ['blur', 'change']
          }]
        }
      }
    }
  },
  data() {
    return {
      show: true,
      form_: {},
      formConfig_: {},
      type: this.isEdit
    }
  },
  methods: {
    confirm() {
      if(this.status === 'info'){
        this.cancel()
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const form = _.cloneDeep(this.form_)
          this.formConfig_.list.forEach(e => {
            if (e.dataType === 'json') {
              form[e.prop] = JSON.stringify(form[e.prop])
            }
          })
          if(this.formConfig_.confirmFuc){
            const result = this.formConfig_.confirmFuc(form)
            console.log('校验 ：',result)
            if(result){
              this.$emit('confirm', form)
            }
          }else{
            this.$emit('confirm', form)
          }
        }
      });
    },
    cancel() {
      this.$emit('cancel')
    }
  },
  watch: {
    formConfig: {
      async handler(newVal, oldVal) {
        if (newVal) {
          console.log('newVal :', newVal)
          this.formConfig_ = _.cloneDeep(newVal)
          for (const item of this.formConfig_.list) {
            if (item.options && item.options instanceof Promise) {
              item.options = (await item.options).data
            }
          }
          // this.formConfig_.list.forEach(e => {
          //   this.$set(this.form_, e.prop, '')
          //   // this.form_[e.prop] = ''
          // })
          //this.form_ = newVal
          console.log('this.form_ :', this.form_)
        }

      },
      immediate: true,
      deep: true
    },
    form: {
      handler(newVal, oldVal) {
        if (newVal) {
          console.log('form newVal:', newVal)
          if (newVal) {
            const val = _.cloneDeep(newVal)
            this.formConfig_.list.forEach(e => {
              if (e.dataType === 'json') {
                val[e.prop] = atools.$jsonParse(val[e.prop])
              }
              if (e.func) {
                val[e.prop] = e.func(val[e.prop])
              }
            })
            this.form_ = val
          }
        }
      },
      immediate: true,
      deep: true
    }
  }

}
</script>

<style scoped lang="scss">

</style>
